package com.action.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.action.childbase.ChildBaseActivity;
import com.action.entity.Redpacket;
import com.action.entity.WXPAYBEAN;
import com.action.entity.event.PayResultBackEven;
import com.action.entity.event.RedPacketChangeEvent;
import com.action.entity.event.SwitchAssetEvent;
import com.action.handle.AlipayHandler;
import com.action.service.pressenter.GiveRedPacketPresenter;
import com.action.ui.adapter.AddImageAdapter;
import com.action.utils.GridDividerItemDecoration;
import com.action.utils.LocalCredentialProvider;
import com.action.utils.SingleClick;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alipay.sdk.app.PayTask;
import com.base.app_core.App;
import com.base.app_core.base.ActionPacketView;
import com.base.app_core.model.Paginated;
import com.base.app_core.model.RedPacketVo;
import com.base.app_core.model.dto.CosVo;
import com.base.app_core.model.dto.LocationDto;
import com.base.app_core.service.user.model.HomeRxBean;
import com.base.app_core.service.user.model.User;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.BeanPropertiesUtil;
import com.base.app_core.util.ImageUtils;
import com.base.app_core.util.MD5Util;
import com.base.app_core.util.MaterialDialogHelper;
import com.base.app_core.util.XYBAUtils;
import com.base.app_core.util.log.F;
import com.blankj.utilcode.util.SDCardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.thread.EventThread;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.model.object.PutObjectRequest;
import com.tencent.cos.xml.model.object.PutObjectResult;
import com.tencent.map.lib.util.StringUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.xinglai.yun.R;

import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.iwf.photopicker.PhotoPicker;

@Route(path = AppConstants.ROUTEURI.GIVE_REDPACKET)
public class SendRedPacketActivity extends ChildBaseActivity<GiveRedPacketPresenter> implements ActionPacketView.GiveRedPacketView,
        AddImageAdapter.onDefaultImageAddLisener, ActionPacketView.payView, ActionPacketView.callBackView {

    private static final int SELECT_LOCATION = 0X08;
    private static final int SET_PASSWORD = 0X09;

    @BindView(R.id.img_container)
    RecyclerView imgContainer;

    @BindView(R.id.et_send_redpacket)
    EditText edSendPacket;

    @BindView(R.id.amount)
    EditText etAmount;

    @BindView(R.id.num)
    EditText etNum;

    @BindView(R.id.close_category_list)
    ImageView mclose_category_list;

    @BindView(R.id.tv_password)
    EditText tvPassword;

    @BindView(R.id.submit)
    Button submit;

    @BindView(R.id.rangeTv)
    TextView rangeTv;
    @BindView(R.id.km1)
    TextView txtkm1;
    @BindView(R.id.km2)
    TextView txtkm2;
    @BindView(R.id.km3)
    TextView txtkm3;
    @BindView(R.id.ll_password)
    LinearLayout llPassWord;

    private int payType = 0;

    private AddImageAdapter addImageAdapter;

    /**
     * image展示
     */
    public List<String> imagesViews = new ArrayList<>();
    /**
     * 本地上传的容器
     */
    public List<String> imageLocal = new ArrayList<>();
    /**
     * 定位view
     */
    @Inject
    LocationDto locationDto;

    @Inject
    CosVo cosVo;

    @Inject
    User user;

    private String encrypt;

    private Disposable payResultDis;

    private RedPacketVo redPacketVo;

    private String password;

    private CosXmlService cosXmlService;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_give_red_packet;
    }

    @Override
    protected void initView() {
        super.initView();
        setToolBar("发红包");
        setImageResource();
        initCos();
        switchReleaseView(releaseAdFanWei);
        RxBus.get().register(this);
    }


    private void initCos() {
        if (cosXmlService == null) {
            String appid = "1257591116";
            String region ="ap-chengdu";
            String secretId = "AKIDAEeuzslz5Ws20oFrjeVDk5INFzXeiNp5";
            String secretKey = "fE0v9FoKiuyqW0JSJ5pQq7HKG5vdNJ7k";
            long keyDuration = 600; //SecretKey 的有效时间，单位秒

            CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder()
                    .setAppidAndRegion(appid, region)
                    .setDebuggable(true)
                    .builder();
            LocalCredentialProvider localCredentialProvider = new LocalCredentialProvider(secretId, secretKey, keyDuration);
            Context context = getApplicationContext(); //应用的上下文
            cosXmlService = new CosXmlService(context, serviceConfig, localCredentialProvider);
        } else {
            F.w("只能初始化一次");
        }
    }

    @OnClick({R.id.km1,R.id.km2,R.id.km3})
    public void selectReleaseRegion(View view){
        switch (view.getId()) {
            case R.id.km1:
                switchReleaseView(1);
                break;
            case R.id.km2:
                switchReleaseView(2);
                break;
            case R.id.km3:
                switchReleaseView(3);
                break;
        }
    }
    private int releaseAdFanWei=1;
    private void switchReleaseView(int i) {
        releaseAdFanWei=i;
        switch (i){
            case 1:
                txtkm1.setSelected(true);
                txtkm2.setSelected(false);
                txtkm3.setSelected(false);
                break;
            case 2:
                txtkm1.setSelected(false);
                txtkm2.setSelected(true);
                txtkm3.setSelected(false);
                break;
            case 3:
                txtkm1.setSelected(false);
                txtkm2.setSelected(false);
                txtkm3.setSelected(true);
                break;
        }
    }

    private void setImageResource() {
        imagesViews.add(AppConstants.Const.ADDIMAGETAG);
        addImageAdapter = new AddImageAdapter();
        GridLayoutManager layout = new GridLayoutManager(this, 4);
        imgContainer.setLayoutManager(layout);
        imgContainer.addItemDecoration(new GridDividerItemDecoration(XYBAUtils.dip2px(8), getResources().getColor(R.color.white)));
        imgContainer.setAdapter(addImageAdapter);
        if (addImageAdapter != null) {
            addImageAdapter.setOnDefaultImageAddLisener(this);
        }
        addImageAdapter.notifyDataSetChanged(imagesViews);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void consumePayResultBackEven(PayResultBackEven t) throws Exception {
        dismissProgress();
        //支付成功
        if (t.getErrCode() == AppConstants.PAY_SUCCESS) {
            RedPacketChangeEvent event = new RedPacketChangeEvent();
            event.setStatus(RedPacketChangeEvent.PACKET_SEND_ED);
            if (redPacketVo != null) {
                Redpacket redpacket = new Redpacket();
                BeanPropertiesUtil.copyProperties(redPacketVo, redpacket);
                redpacket.setWxIcon(user.getWxIcon());
                redpacket.setWxNickname(user.getWxNickname());
                redpacket.setType(0);
                if (!StringUtils.isEmpty(tvPassword.getText().toString())) {
                    redpacket.setType(1);//密码红包
                }
                event.setRedpacket(redpacket);
                RxBus.get().post(new HomeRxBean(HomeRxBean.SEND_REDPACKET, event));
                RxBus.get().post(new SwitchAssetEvent(0));
            }
            showToast("支付成功");
            finish();
        } else if (t.getErrCode() == AppConstants.PAY_ERROR) {//错误
            MaterialDialogHelper.showSingleText(SendRedPacketActivity.this, "支付遇到问题了?", "取消", "再试一次", new MaterialDialogHelper.onItemClickLisener() {
                @Override
                public void onPosiClick(MaterialDialog dialog, DialogAction which) {
                    if (redPacketVo != null && !StringUtils.isEmpty(redPacketVo.getSn())) {
                        payAction(redPacketVo.getSn());
                    }
                }

                @Override
                public void onNatiClick(MaterialDialog dialog, DialogAction which) {
                    dialog.dismiss();
                }
            });
        } else if (t.getErrCode() == AppConstants.PAY_CANCEL) {//用户取消
            MaterialDialogHelper.showSingleText(SendRedPacketActivity.this, "支付遇到问题了?",
                    "取消", "再试一次", new MaterialDialogHelper.onItemClickLisener() {
                        @Override
                        public void onPosiClick(MaterialDialog dialog, DialogAction which) {
                            if (redPacketVo != null && !StringUtils.isEmpty(redPacketVo.getSn())) {
                                payAction(redPacketVo.getSn());
                            }
                        }

                        @Override
                        public void onNatiClick(MaterialDialog dialog, DialogAction which) {
                            dialog.dismiss();
                        }
                    });
        }
    }


    @Override
    protected void initData() {
        super.initData();
        App.getApp().regToWx();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
        if (addImageAdapter != null) {
            addImageAdapter.setOnDefaultImageAddLisener(null);
        }

//        if (App.getApp().iwxapi != null) {
//            App.getApp().iwxapi.detach();
//        }
    }

    @Override
    protected String[] getPermissions() {
        return new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION};
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    @OnClick({R.id.ll_password, R.id.ll_location, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_password:
                break;
            case R.id.submit:
                if (SingleClick.isSingle()) {
                    checkAd();
                }
                break;
        }
    }


    private void checkAd() {
        String content = edSendPacket.getText().toString().trim();
        if (StringUtil.isEmpty(content)) {
            showToast("广告内容必须填写");
            return;
        }

//        if (imagesViews.size() < 2) {
//            showToast("请至少选择一张广告图");
//            return;
//        }

        int num = 0;
        try {
            String trim = etNum.getText().toString().trim();
            if (StringUtil.isEmpty(trim)) {
                showToast("请输入广告数量");
                return;
            }

            num = Integer.parseInt(trim);
            if (num == 0) {
                showToast("请输入广告数量");
                return;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        BigDecimal amount = null;

        String trim = etAmount.getText().toString().trim();
        if (StringUtil.isEmpty(trim)) {
            showToast("请输入广告金额");
            return;
        }
        amount = new BigDecimal(trim);
        if (amount.setScale(2, RoundingMode.DOWN).compareTo(new BigDecimal(200).multiply(new BigDecimal(num)).setScale(2, RoundingMode.DOWN)) > 0) {
            showToast("单个广告金额最高200元");
            return;
        }

        if (amount.setScale(2, RoundingMode.DOWN).compareTo(new BigDecimal(0.1).setScale(2, RoundingMode.DOWN)) < 0 ||
                amount.setScale(2, RoundingMode.DOWN).compareTo(new BigDecimal(0.1).multiply(new BigDecimal(num)).setScale(2, RoundingMode.DOWN)) < 0) {
            showToast("单个广告金额最低0.1元");
            return;
        }

        if (locationDto.getLatitude() == 0 || locationDto.getLongitude() == 0) {
            return;
        }

        if (!SDCardUtils.isSDCardEnable()) {
            showToast("SD卡存储卡异常,请检查");
            return;
        }
        submit(content, num, amount);
    }

    private void submit(final String content, final int num, final BigDecimal amount) {
        //UploadService 封装了上述分片上传请求一系列过程的类
        showProgress();
        new AsyncTask<Void, Void, List<String>>() {
            @Override
            protected List<String> doInBackground(Void... lists) {
                List<String> imageUpload = new ArrayList<>();
                for (String images : imageLocal) {
                    String bucket = "xinglaiyun-1257591116"; // cos v5 的 bucket格式为：xxx-appid, 如 isTest-1253960454
                    String cosPath = images.replace(SDCardUtils.getDataPath(), ""); //格式如 cosPath = "isTest.txt";
                    String srcPath = images; // 如 srcPath = Environment.getExternalStorageDirectory().getPath() + "/isTest.txt";
                    long signDuration = 600; //签名的有效期，单位为秒
                    PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, cosPath, srcPath);
                    putObjectRequest.setSign(signDuration, null, null); //若不调用，则默认使用sdk中sign duration（60s）
                    try {
                        PutObjectResult putObjectResult = cosXmlService.putObject(putObjectRequest);
                        String accessUrl = null;
                        if (!putObjectResult.accessUrl.startsWith("http")) {
                            accessUrl = "http://" + putObjectResult.accessUrl;
                        } else {
                            accessUrl = putObjectResult.accessUrl;
                        }
                        imageUpload.add(accessUrl);
                    } catch (CosXmlClientException e) {
                        break;
                    } catch (CosXmlServiceException e) {
                        break;
                    } catch (Exception ee) {
                        ee.printStackTrace();
                    }
                }
                return imageUpload;
            }

            @Override
            protected void onPostExecute(List<String> imageUpload) {
                StringBuffer buffer = new StringBuffer();
                if (!XYBAUtils.isEmpty(imageUpload)) {
                    for (String img : imageUpload) {
                        buffer.append(img).append(",");
                    }
                    buffer.deleteCharAt(buffer.length() - 1);
                }
                if(releaseAdFanWei==1)
                    locationDto.setRange(1000);
                else if(releaseAdFanWei==2)
                    locationDto.setRange(-1);
                else if(releaseAdFanWei==3)
                    locationDto.setRange(-3);
                if(!StringUtils.isEmpty(tvPassword.getText().toString())){
                    encrypt = MD5Util.encrypt(tvPassword.getText().toString());
                }
                mPresenter.sendPacket(content, num, amount, encrypt, locationDto.getRange(),
                        String.valueOf(locationDto.getLongitude()), String.valueOf(locationDto.getLatitude()),
                        buffer.toString(), locationDto.getProvinceCode(), locationDto.getCityCode(), locationDto.getAreaCode(),
                        "");
            }
        }.execute();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }

        if (requestCode == SELECT_LOCATION) {
            LocationDto l = data.getParcelableExtra(AppConstants.EXTRA.LOCATION_INFO);
            try {
                BeanPropertiesUtil.copyProperties(l, locationDto);
                int range = locationDto.getRange();
                if (range > 0) {
                    rangeTv.setText(range / 1000 + "公里");
                } else {
                    if (range == -3) {
                        rangeTv.setText("全国");
                    } else if (range == -2) {
                        rangeTv.setText(locationDto.getProvince());
                    } else if (range == -1) {
                        rangeTv.setText(locationDto.getCity());
                    } else if (range == 0) {
                        rangeTv.setText(locationDto.getDistrict());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == SET_PASSWORD) {
            password = data.getStringExtra(SetPacketPasswordActivity.PASSWORD);
            if (!StringUtils.isEmpty(password)) {
                tvPassword.setText(password);
                encrypt = MD5Util.encrypt(password);
            } else {
                tvPassword.setText("");
                encrypt = null;
            }
        } else if (requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (photos != null && photos.size() == 1) {
                    //进行压缩
                    String fileimagesrc = photos.get(0);
                    try {
                        String fileName = SDCardUtils.getDataPath() + MD5Util.encrypt(String.valueOf(System.currentTimeMillis())) + ".jpg";
                        ImageUtils.compressImage(fileimagesrc, fileName, 50);
                        fetchImage(fileName);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        showToast("手机存储异常");
                    }
                }
            }
        } else if (resultCode == RESULT_OK && requestCode == AddImageAdapter.REQUEST_CODE) {
            ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            imagesViews.clear();
            imagesViews.addAll(photos);
            addImageAdapter.notifyDataSetChanged(imagesViews);
        }
    }

    public void fetchImage(String s) {
        imagesViews.add(imagesViews.size() - 1, s);
        if (imagesViews.size() == AppConstants.PACKAGE_IMAGE_LENGHT) {
            imagesViews.remove(imagesViews.size() - 1);
        }
        imageLocal.add(s);
        addImageAdapter.notifyDataSetChanged(imagesViews);
    }

    @Override
    public void notifyError(String errorCode, String content) {
        super.notifyError(errorCode, content);
    }

    /**
     * 进入支付环节
     *
     * @param data
     */
    @Override
    public void onGiveSuccess(RedPacketVo data) {
        redPacketVo = data;
        dismissProgress();
        //进入支付环节
        if (data != null && !StringUtil.isEmpty(data.getSn())) {
            payAction(data.getSn());
        } else {
            showToast("广告订单号错误");
        }
    }


    private void payAction(String data) {
        if (payType == AppConstants.Const.PAYTYPE_WEICHAT) {
            showToast("正在跳转微信支付");
            if (XYBAUtils.checkApkExist(this)) {
                showProgress();
                mPresenter.WXPay(data);
            } else {
                showToast("您尚未安装微信");
            }
        } else if (payType == AppConstants.Const.PAYTYPE_ALI) {//支付宝支付
            showToast("正在跳转支付宝支付");
            showProgress();
            mPresenter.AliPay(data);
        }
    }

    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        dismissProgress();
        if (object instanceof WXPAYBEAN) {
            PayReq req = new PayReq();
            req.appId = ((WXPAYBEAN) object).getAppid();
            req.partnerId = ((WXPAYBEAN) object).getPartnerid();
            req.packageValue = ((WXPAYBEAN) object).getPackageX();
            req.sign = ((WXPAYBEAN) object).getSign();
            req.prepayId = ((WXPAYBEAN) object).getPrepayid();
            req.nonceStr = ((WXPAYBEAN) object).getNoncestr();
            req.timeStamp = ((WXPAYBEAN) object).getTimestamp();
            boolean bstatu = App.getApp().iwxapi.sendReq(req);
            F.j("status:" + bstatu);
        }
    }

    @Override
    public void onClickAction(boolean b, String item) {
        if (b) {
            addImageAdapter.previewImage(this, item);
        } else {
            RxPermissions rxPermission = new RxPermissions(this);
            if (rxPermission.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                doSelectPicture();
            } else {
                rxPermission.request(android.Manifest.permission.ACCESS_COARSE_LOCATION).subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            doSelectPicture();
                        } else {
                            MaterialDialogHelper.showSingleText(SendRedPacketActivity.this,
                                    "需要权限才能发广告照片呢~ 请赐予我们吧~ 谢谢", "取消", "授予权限",
                                    new MaterialDialogHelper.onItemClickLisener() {
                                        @Override
                                        public void onPosiClick(MaterialDialog dialog, DialogAction which) {
                                            doSelectPicture();
                                        }

                                        @Override
                                        public void onNatiClick(MaterialDialog dialog, DialogAction which) {
                                            dialog.dismiss();
                                        }
                                    });
                        }
                    }
                });
            }
        }
    }

    private void doSelectPicture() {
        if (SingleClick.isSingle()) {
            PhotoPicker.builder()
                    .setPhotoCount(1)
                    .setShowCamera(true)
                    .setShowGif(false)
                    .setPreviewEnabled(true)
                    .setShowCamera(true)
                    .start(this, PhotoPicker.REQUEST_CODE);
        }
    }

    @Override
    public void AliPayRequest(final String data) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                PayTask payTask = new PayTask(SendRedPacketActivity.this);
                String result = payTask.pay(data, true);
                Message msg = new Message();
                msg.what = AlipayHandler.SDK_PAY_FLAG;
                msg.obj = result;
                F.j(result);
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }

    @Override
    public void doHandleSuccess() {
        RxBus.get().post(new PayResultBackEven(AppConstants.PAY_SUCCESS));
    }
}
